const util = require('../../../utils/util.js')
const domainName = getApp().globalData.domainName
const oss_domain = getApp().globalData.oss_domain
const parameter = getApp().globalData.parameter

const jg_stu_id = wx.getStorageSync('jg_stu_id') || ''

// 判卷
const grade_paper=(that)=>{
  let array = that.data.ti_list
  const result = array.reduce((acc,  item) => {
    if (item.result === 1) acc.correct++; 
    if (item.result === 2) {
      acc.wrong++;
      acc.wrongs.push({question_id:item.id, selected_id:item.select, read_at:item.start_read_time, select_at:item.select_time});
    }; 
    if (item.select) {
      acc.finished++; 
      acc.finished_questions.push({question:item.id, selected:item.select, read_at:item.start_read_time, select_at:item.select_time, result:item.result, chapter:item.chapter.code, section:item.section})
    }; 
    return acc;
    // 完成数量、正确数量、错误数量、错误习题、阅读时间、选择时间、是否正确。
  }, {finished: 0, correct: 0, wrong: 0, wrongs:[],finished_questions:[]});
  return result
}

// 提交
const submit_=(that, showText)=>{
  var transcript = grade_paper(that)
  wx.showLoading({
    title: '大量数据上传中……',
    mask:true,
  })
  var submit_time = new Date()
  // “~~”=取整数部分
  var cost = ~~(Math.abs(new Date(submit_time).getTime() - new Date(that.data.start_time).getTime())/1000)
  var formData = {
    test_paper:that.data.test_paper_info.id,
    // 应该使用实际题量（因为可能后端不够设置的题量）
    capacity:that.data.ti_list.length,
    test_type:that.data.test_paper_info.id?'uniform':'self',
    student:this.data.userInfo.relative_jgs.student_jg?.student,
    start_time:that.data.start_time,
    submit_time:util.formatTime(submit_time),
    cost:cost,
    finished: transcript.finished,
    correct: transcript.correct,
    wrong: transcript.wrong,
    finished_questions: transcript.finished_questions,
  }
  wx.request({
    url: domainName + 'questions/transcript/create',
    data: formData,
    method:'POST',    
    header:header,
    success: res => {
      wx.hideLoading()
      console.log('res', res)
      const res_data = res.data
      if(res.data.result==1){
        clearInterval(that.data.timer_id)
        wx.showModal({
          content: showText || '提交完成！',
          showCancel: false,
          title: '提示',
          success: res => {
            wx.reLaunch({
              url: '/pages/doTi/transcript_detail/transcript_detail?transcript=' + encodeURIComponent(JSON.stringify({
                wrongs:transcript.wrongs, ...res_data.data
              })),
            })
          },
        })
      }else{
        let content = res.data.data.detail
        wx.showModal({
          content: content,
          showCancel: false,
          title: '提示！',
        })
      }
    },
    fail:err=>{
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  })

}


// 提交打分
const submit_opt=(that)=>{
  let unfinished = that.data.ti_list.length - that.data.finished
  if(!jg_stu_id){
    wx.showModal({
      content: '抱歉，未检测到您的学号，请联系客服',
      showCancel: false,
      title: '提示',
    })
  }else if(!that.test_paper_id){
    wx.showModal({
      content: '抱歉，未检测到试卷号，请联系客服',
      showCancel: false,
      title: '提示',
    })
  }else if(unfinished>0){
    wx.showModal({
      content: '未做 ' + unfinished + ' 题，确定提交吗？',
      title: '提醒',
      success: res => {
        if(res.confirm){
          // console.log('提交')
          submit(that)
        }
      },
    })
  }else{
    wx.showModal({
      content: '确定要提交吗？',
      showCancel: true,
      title: '提示',
      success: res => {
        if(res.confirm){
          submit(that)
        }
      },
    })
  }
}

// 提交
const submit=(that, showText)=>{
  wx.showLoading({
    title: '大量数据上传中……',
    mask:true,
  })
  wx.request({
    url: domainName + '/do_test_submit',
    data: {
      jg_stu_id:jg_stu_id,
      test_paper_id:that.test_paper_id,
      start_time:that.start_time,
      end_time:util.formatTime(new Date()),
      ti_list:JSON.stringify(that.data.ti_list),
    },...parameter,
    success: res => {
      wx.hideLoading()
      let transcript_id = res.data.row_id
      if(transcript_id=='已提交'){
        wx.showModal({
          content: '勿重复提交',
          showCancel: false,
          title: '提示',
        })
      }else if(transcript_id){
        clearInterval(that.data.timer_id)
        wx.showModal({
          content: showText || '提交完成！',
          showCancel: false,
          title: '提示',
          success: res => {
            wx.reLaunch({
              url: '/pages/doTi/transcript_details/transcript_details?transcript_id=' + transcript_id,
            })
          },
        })
      }else{
        wx.showToast({
          title: '提交失败',
          duration: 2000,
          icon: 'error',
          mask: false,
        })
      }
    },
    fail:err=>{
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  })

}
// 收藏题
const set_bookmark=(that,jg_stu_id)=>{
  if(!jg_stu_id){
    wx.showModal({
      content: '在训学员方可收藏习题！',
      title: '提示',
    })
    return
  }
  let ti_id = that.data.ti_list[that.data.current_list_index].ti_id
  wx.request({
    url: domainName + '/do_test_add_bookmarkTi',
    data: {
      ti_id:ti_id,
      jg_stu_id:jg_stu_id,
      test_paper_id:that.test_paper_id,
    },
    ...parameter,
    success: res => {
      getApp().get_vibration()
      that.setData({
        ti_bookmarks:res.data.lis
      })
    },
  })
}

const count_finished = (list) => {
  var finished = 0
  for(var i=0;i<list.length;i++){
    if(list[i].select && list[i].result){
      finished += 1
    }
  }
  return finished
}

// 滑动swiper事件
const swiperchange=(that,e)=>{
    // console.log('滑动swiper事件',e)
    let source = e.detail.source
    if(source=="touch"){
      var current = e.detail.current
      var list_show = that.data.list_show
      // console.log('last_current_index',that.data.last_current_index)
      // console.log('current',current)
      // 以下为前进
      if(that.data.last_current_index==0 && current==1){
        // console.log('0-1')

        var current_dic = that.data.ti_list[that.data.current_list_index+2]
        if(current_dic){
          list_show.splice(2,1,current_dic)   // 将索引为2的滑块内容换为题 current_dic
          that.setData({
            current_list_index:that.data.current_list_index + 1,
            list_show:list_show,
            last_current_index:current,
          })
        }else{
          go_ti_now(that,that.data.ti_list.length-1)
        }
      }else if(that.data.last_current_index==1 && current==2){
        // console.log('1-2')  // 正常的，不用处理
        var current_dic = that.data.ti_list[that.data.current_list_index+2]
        list_show.splice(0,1,current_dic)  // 将索引为0的滑块内容换为题 current_dic
        that.setData({
          current_list_index:that.data.current_list_index + 1,
          list_show:list_show,
          last_current_index:current,
        })
      }else if(that.data.last_current_index==2 && current == 0){
        // console.log('2-0')
        var current_dic = that.data.ti_list[that.data.current_list_index+2]
        if(current_dic){
          list_show.splice(1,1,current_dic)  // 将索引为1的滑块内容换为题 current_dic
          that.setData({
            current_list_index:that.data.current_list_index + 1,
            list_show:list_show,
            last_current_index:current,
          })
        }else{
          go_ti_now(that,that.data.ti_list.length-1)
        }

        // 以下为后退
      }else if(that.data.last_current_index==1 && current == 0){
        // console.log('1-0')
        var current_dic = that.data.ti_list[that.data.current_list_index-2]
        if(current_dic){
          list_show.splice(2,1,current_dic) // 将索引为1的滑块内容换为题 current_dic
          that.setData({
            list_show:list_show,
            last_current_index:current,
            current_list_index:that.data.current_list_index - 1,
          })
        }else{
          go_ti_now(that,0)
        }
      }else if(that.data.last_current_index==0 && current == 2){
        // console.log('0-2')
        var current_dic = that.data.ti_list[that.data.current_list_index-2]
        if(current_dic){
          list_show.splice(1,1,current_dic)  // 将索引为1的滑块内容换为题 current_dic
          that.setData({
            list_show:list_show,
            last_current_index:current,
            current_list_index:that.data.current_list_index - 1,
          })
        }else{
          go_ti_now(that,0)
        }
      }else if(that.data.last_current_index==2 && current == 1){
        // console.log('2-1')
        var current_dic = that.data.ti_list[that.data.current_list_index-2]
        list_show.splice(0,1,current_dic)  // 将索引为1的滑块内容换为题 current_dic
        that.setData({
          current_list_index:that.data.current_list_index - 1,
          list_show:list_show,
          last_current_index:current,
        })
      }
      that.setData({
        start_read_time:util.formatTime(new Date()),  // 记录开始读题时间
      })
    }
  }  
// 选定习题
const go_ti=(that,e)=>{
  let index = parseInt(e.currentTarget.id)
  go_ti_now(that,index)
}
// 前往习题
const go_ti_now=(that,index)=>{
  if(index==0){
    that.setData({
      current_index:0,
      list_show:that.data.ti_list.slice(index,index+2).concat({}),
      last_current_index:0, // 默认最近current==0
    })
  }else if(index+1==that.data.ti_list.length){
    that.setData({
      current_index:2,
      list_show:[{}].concat(that.data.ti_list.slice(index-1,that.data.ti_list.length)),
      last_current_index:2, // 默认最近current==2
    })
  }else{
    that.setData({
      current_index:1,
      list_show:that.data.ti_list.slice(index-1,index+2),
      last_current_index:1, // 默认最近current==1
    })
  }
  that.setData({
    current_list_index:index,
    start_read_time:util.formatTime(new Date()),
  })
  // 关闭抽屉
  close_drawer(that)
}
// 开始选择
const sel=(that,e)=>{
  // console.log('开始选择')
  let select = e.currentTarget.id
  // console.log('select',select)
  let index = e.currentTarget.dataset.index
  let list_show = that.data.list_show
  // 对比答案，并写入结果
  if(select==list_show[index].answer){
    var result = 1  // 正确
  }else{
    var result = 2  // 错误
  }
  // 将所选答案写入
  list_show[index].select= select
  list_show[index].result= result
  list_show[index].start_read_time= that.data.start_read_time
  list_show[index].select_time= util.formatTime(new Date())
  // 计算已做习题题量
  let finished = count_finished(that.data.ti_list)
  that.setData({
    list_show:list_show,
    ti_list:that.data.ti_list,
    finished:finished,
  })

}
// 查看答题卡
const open_drawer=(that)=>{that.setData({view_card:true})}
//关闭答题卡
const close_drawer=(that)=>{that.setData({view_card:false})}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ti_bookmarks : [],
    ti_list : [{ti_id:null}],
    icon_url:oss_domain + 'static/picture/app_icon/',
    view_card:false,
    count_down:600, // 默认时间600秒
    finished:0,
    current_list_index:0,
    last_current_index:0,
  },
    // 倒计时
  count_down(test_duration){
    var timer_id = setInterval(() => {
      if(this.data.count_down>0){
        this.setData({
          count_down:this.data.count_down - 1,
        })    
      }else{
        clearInterval(this.data.timer_id)
        let showText = '时间到！已自动提交试卷！'
        submit(this, showText)
      }
    }, 1000);
    this.setData({
      timer_id:timer_id,
      count_down:test_duration,
    })
  },

  // 滑动页面
  swiperchange(e){swiperchange(this,e)},
  // 查看答题卡
  open_drawer(){open_drawer(this)},
  //关闭答题卡
  close_drawer(){close_drawer(this)},
  // 前往指定习题
  go_ti(e){getApp().get_vibration();go_ti(this,e)},
  // 提交询问
  submit_opt(e){getApp().get_vibration();submit_opt(this,e)},
  // 收藏习题
  set_bookmark(e){getApp().get_vibration();set_bookmark(this,jg_stu_id)},
  // 点击选题
  sel(e){getApp().get_vibration();sel(this,e)},

  // 初始化加载题
  page_init(jg_stu_id, test_paper_id){
    wx.showLoading({
      title: '连接题库中……',
      mask: false,
    })
    wx.request({
      url: domainName + '/do_test_init',
      data: {
        jg_stu_id:jg_stu_id,
        test_paper_id:test_paper_id,
      },...parameter,
      success: res => {
        wx.hideLoading()
        // console.log('res.data',res.data)
        let ti_list = res.data.ti_list
        let test_duration = res.data.test_duration
        var list_show = ti_list.slice(0,3)
        this.setData({
          ti_list:ti_list,
          list_show:list_show,
          start_read_time:util.formatTime(new Date()),  // 记录开始读题时间

          ti_bookmarks:res.data.ti_bookmarks, // 该学员的收藏题库
        })
        this.count_down(test_duration)
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log('options',options)
    this.test_paper_id = options.test_paper_id
    this.page_init(jg_stu_id, this.test_paper_id)
    this.jg_stu_id = jg_stu_id
    this.start_time = util.formatTime(new Date())
  },

  onUnload(){
    // 清楚定时器
    clearInterval(this.data.timer_id)
    // console.log('清楚定时器')
  },

  onReady(){
    this.setData({
      windowHeight : wx.getSystemInfoSync().windowHeight,
    })
  }

})